package com.rental.houses.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rental.common.constant.RedisConstant;
import com.rental.common.result.AjaxResult;
import com.rental.houses.mapper.RequiredHouseMapper;
import com.rental.houses.service.RequiredHouseService;
import com.rental.model.entity.house.RequiredHouse;

import com.rental.model.entity.house.RequiredReport;
import com.rental.model.form.house.RequiredHouseForm;

import com.rental.model.form.house.RequiredHousePage;
import com.rental.model.form.house.RequiredReportForm;
import com.rental.model.vo.house.HouseTypeVo;
import com.rental.model.vo.house.RequiredHouseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class RequiredHouseServiceImpl extends ServiceImpl<RequiredHouseMapper, RequiredHouse> implements RequiredHouseService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override

    public Boolean addRequiredHouse(RequiredHouseForm requiredHouseForm) {
//        将接受的数据转换为实体类进行保存
        RequiredHouse requiredHouse = new RequiredHouse();

        try {

            BeanUtils.copyProperties(requiredHouseForm, requiredHouse);
            boolean isSave = save(requiredHouse);
            if (!isSave) {
                return false;
            }
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
        // 将发布的房屋id存入Redis
        redisTemplate.boundZSetOps(RedisConstant.USER_PUBLISH_KEY + requiredHouseForm.getUid()).add(HouseTypeVo.build(3, requiredHouse.getId()), System.currentTimeMillis());
        return true;

    }



//    @Override
//    public RequiredHouseVo getRequiredHouseList() {
////        redis判断是否有缓存，如果有就直接返回，如果没有就查询数据库并返回
//        if (!redisTemplate.hasKey(RedisConstant.USER_RequiredList_KEY)) {
//            //        查询列表并封装返回
//            List<RequiredHouse> list = list();
//            RequiredHouseVo requiredHouseVo = new RequiredHouseVo();
//            requiredHouseVo.setRequiredHouseList(list);
////            并设置半小时的过期时间
//            redisTemplate.opsForValue().set(RedisConstant.USER_RequiredList_KEY, requiredHouseVo, 30, TimeUnit.MINUTES);
//        }
//        return (RequiredHouseVo) redisTemplate.opsForValue().get(RedisConstant.USER_RequiredList_KEY);
//    }


    @Override
    public RequiredHouseVo getRequiredHouseDetail(Long id) {
//        根据id查询详情并封装返回,每一次查询都相当于有人浏览量一次那么就要加1
        RequiredHouse requiredHouse = getById(id);
        RequiredHouseVo requiredHouseVo = new RequiredHouseVo();
        BeanUtils.copyProperties(requiredHouse, requiredHouseVo);
//        设置头像
        requiredHouseVo.setPhoto(requiredHouse.getPhoto());
        boolean isUpdate = update().setSql("view_count = view_count + 1").eq("id", id).update();
        if (!isUpdate) {
            throw new RuntimeException("更新失败");
        }
        return requiredHouseVo;
    }

    @Override
    public Boolean deleteRequiredHouse(Long id) {
//        根据id删除个人求租信息
        return removeById(id);
    }

    /**
     * 获取当前用户的所有求租房屋信息
     * @param uid
     * @return
     */
    @Override
    public List<RequiredHouse> getRequiredHouseListByUid(Long uid) {
        LambdaQueryWrapper<RequiredHouse> eq = new LambdaQueryWrapper<RequiredHouse>().eq(RequiredHouse::getUid, uid);
        List<RequiredHouse> requiredHouseList = this.list(eq);
        return requiredHouseList;
    }
    @Override
    public Boolean updateRequiredHouse(RequiredHouseForm requiredHouseForm) {
//        修改个人求租信息
        RequiredHouse requiredHouse = new RequiredHouse();
        BeanUtils.copyProperties(requiredHouseForm, requiredHouse);
        return updateById(requiredHouse);
    }

    @Override
    public RequiredHouseVo getRequiredHouseById(Long id, Long userId) {
//        根据id查询出详情并封装返回
        RequiredHouse requiredHouse = getById(id);
        RequiredHouseVo requiredHouseVo = new RequiredHouseVo();
        BeanUtils.copyProperties(requiredHouse, requiredHouseVo);
//        浏览记录
        boolean update = update().setSql("view_count = view_count + 1").eq("id", id).update();
        if (!update) {
            throw new RuntimeException("更新失败");
        }

        redisTemplate.boundZSetOps(RedisConstant.USER_VISIT_HISTORY_KEY + userId).add(HouseTypeVo.build(3, id), System.currentTimeMillis());
        return requiredHouseVo;
    }

    @Override
    public Boolean reportRequiredHouse(RequiredReportForm requiredReportForm) {
//        将举报信息保存到redis中
        RequiredReport requiredReport = new RequiredReport();
        BeanUtils.copyProperties(requiredReportForm, requiredReport);
        redisTemplate.opsForValue().set(RedisConstant.USER_RequiredReport_KEY, requiredReport, 30, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public Boolean collect(Long rid, Long uid) {
        redisTemplate.boundZSetOps(RedisConstant.USER_COLLECTION_KEY + uid).add(HouseTypeVo.build(3, rid), System.currentTimeMillis());
        redisTemplate.boundZSetOps(RedisConstant.USER_VISIT_HISTORY_KEY + uid).add(HouseTypeVo.build(3, rid), System.currentTimeMillis());
        return true;
    }

    @Override
    public Boolean cancelCollect(Long rid, Long uid) {
        redisTemplate.boundZSetOps(RedisConstant.USER_COLLECTION_KEY + uid).remove(HouseTypeVo.build(3, rid));
        return true;
    }

    @Override
    public AjaxResult<Page<RequiredHousePage>> getRequiredHouseList(Long current, Long size, RequiredHouseForm requiredHouseForm) {
        Page<RequiredHouse> page = new Page<>(current, size);
        LambdaQueryWrapper<RequiredHouse> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (requiredHouseForm != null) {
            // 根据需要添加查询条件
        }

        IPage<RequiredHouse> requiredHousePage = this.page(page, wrapper);

        // 将实体类转换为 RequiredHousePage 类
        List<RequiredHousePage> requiredHousePageList = requiredHousePage.getRecords().stream()
                .map(this::convertToRequiredHousePage)
                .collect(Collectors.toList());

        Page<RequiredHousePage> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(requiredHousePageList);

        return AjaxResult.success(voPage);
    }

    private RequiredHousePage convertToRequiredHousePage(RequiredHouse requiredHouse) {
        RequiredHousePage page = new RequiredHousePage();
        BeanUtils.copyProperties(requiredHouse, page);
        return page;
    }





}
